/*
 * @Author: Mainul Islam
 */

package edu.uta.cse.randomgraph.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class LogWriter {

	private boolean ignoreLog;
	public String outputDirectory;
	public String degDistFolderName = "Degree Distribution";
	public String ageDegreeRelationFolderName = "Age-Degree Relation";
	
	private static String rootFolder = "RandomGraph_Log";
	
	private static String summaryFileName = "summary.txt";
	private static String degDistFileName = "degDist.txt";
	private static String unknowFileName = "unknown.txt";
	
	FileWriter fw; 
	BufferedWriter bw; 
	
	
	public LogWriter() {
		outputDirectory = new File(".").getAbsolutePath();
		//outputDirectory = System.getProperty("user.dir");
		init();
	}
	
	public LogWriter(String dir) {
		outputDirectory = dir;
		init();
	}
	
	private void init() {
		if(!outputDirectory.endsWith("/"))
			outputDirectory += "/";
		outputDirectory += rootFolder + "/";
		ignoreLog = !createDirectory(outputDirectory);
	}
	
	public void makeDisable(boolean val) {
		ignoreLog = val;
	}
	
	private boolean isValidDirectory(String  dir) {
		File dirFile = new File(dir);
		return (dirFile.exists() && dirFile.isDirectory());
	}

	public boolean createDirectory(String dirFullPath) {
		if( isValidDirectory(dirFullPath) )
			return true;
		File folder = new File(dirFullPath);
		return folder.mkdir();
	}
	
	public String getLogTypeFileName(LogType lt) {
		switch(lt) {
			case Summary: return summaryFileName;				
			case DegreeDistribution: return degDistFileName;	
		}
		return unknowFileName;
	}
	
	public boolean openWriter(String fullFilePath) {
		try {
			fw = new FileWriter(fullFilePath, true);
			bw = new BufferedWriter(fw); 
		}
		catch (Exception io) {
			return false;
		}
		return true;
	}
	
	public boolean closeWriter() {
		try {
			if(bw != null)
				bw.close();
			if(fw != null)
				fw.close();
		}
		catch (Exception io) {
			return false;
		}
		return true;
	}

	public void writeLine() {
		if(ignoreLog)
			return;
		write("\n");
	}
	
	public void writeLine(int n) {
		if(ignoreLog)
			return;
		write(Integer.toString(n)+"\n");
	}
	
	public void writeLine(double d) {
		if(ignoreLog)
			return;
		write(Double.toString(d)+"\n");
	}
	
	public void writeLine(String s) {
		if(ignoreLog)
			return;
		write(s+"\n");
	}
	
	public void write(int n) {
		if(ignoreLog)
			return;
		write(Integer.toString(n));
	}
	
	public void write(double d) {
		if(ignoreLog)
			return;
		write(Double.toString(d));
	}

	public void write(String s) {
		if(ignoreLog)
			return;
		try{
			bw.write(s);	
		}
		catch (Exception e) {
			return;
		}
	}



}
